<?php
namespace Logic\Member;
use Spartan\Lib\Logic;

!defined('APP_PATH') && exit('404 Not Found');

/**
 * 用户的登录或注册
 * Class Auth
 * @package Logic\Member
 */
class Auth extends Logic
{
    /**
     * 自动登录
     * @return array
     */
    public function memberAuth(){
        $strOpenId = $this->getData('openId','');
        if (!$strOpenId){
            return Array('openId丢失，请重新登录。',0);
        }
        $options = Array(
            'where'=>Array('wx_open_id'=>$strOpenId),
        );
        $arrMemberInfo = $this->Db()->find('member_auth',$options);
        if (!$arrMemberInfo){//还没有用户，注册一个并返回
            return $this->addUser();
        }else{
            return Array('success',1,$arrMemberInfo);
        }
    }

    /**
     * 注册一个用户
     * @return array
     */
    public function addUser(){
        $arrData = Array(
            'wx_open_id'=>$this->getData('openId',''),
            'wx_union_id'=>$this->getData('unionId',''),
            'nick_name'=>$this->getData('nickName',''),
            'face'=>$this->getData('avatarUrl',''),
            'sex'=>$this->getData('gender',''),
            'address'=>$this->getData('country','').';'.
                $this->getData('province','').';'.
                $this->getData('city','').';'.
                $this->getData('address',''),
            'reg_time'=>date('Y-m-d H:i:s',time()),
        );
        (!$arrData['wx_open_id'] && $this->getData('openid')) && $arrData['wx_open_id'] = $this->getData('openid');
        (!$arrData['nick_name'] && $this->getData('nickname')) && $arrData['nick_name'] = $this->getData('nickname');
        (!$arrData['face'] && $this->getData('headimgurl')) && $arrData['face'] = $this->getData('headimgurl');
        (!$arrData['wx_union_id'] && $this->getData('unionid')) && $arrData['wx_union_id'] = $this->getData('unionid');
        $arrData['recommend_code'] = substr(md5($arrData['wx_open_id']), 8, 16);//用户推荐码
        if (!$arrData['wx_open_id']){
            return Array('openId丢失，请重新登录。',0);
        }
        $arrData['user_name'] = $arrData['nick_name'];

        $this->Db()->startTrans('Auth.addUser');
        $intUserId = max(0,$this->Db()->insert('member_auth',$arrData));
        if ($intUserId < 1){
            $this->Db()->rollback();
            return Array('用户登录失败，请联系管理员。',0);
        }
        $this->setData(Array('user_id'=>$intUserId));
        $this->setData(Array('reg_time'=>$arrData['reg_time']));
        //添加用户详细信息
        $arrResult = $this->initUserInfo($intUserId);
        if ($arrResult[1] != 1){
            $this->Db()->rollback();
            return Array('帐号初始化失败，请联系管理员。',0);
        }
        $this->Db()->commit('Auth.addUser');
        $strRecommendCode = $this->getRequestValue('recommend_code','');
        if (mb_strlen($strRecommendCode,'utf-8') == 16){
            Relations::instance([
                'user_id'=>$intUserId,
                'user_name'=>$arrData['user_name'],
                'recommend_code'=>$strRecommendCode,
            ])->addRecommendByCode();
        }
        $options = Array(
            'where'=>Array('id'=>$intUserId),
        );
        $arrMemberInfo = $this->Db()->find('member_auth',$options);
        !$arrMemberInfo && $arrMemberInfo = [];
        return Array('success',1,$arrMemberInfo);
    }

    /**
     * 初始化一个用户
     * @param $intUserId
     * @param $form
     * @return array
     */
    public function initUserInfo($intUserId,$form = 'reg'){
        $this->Db()->startTrans('Auth.addUser');
        $iniTable = Array(
            'member_account' => Array(//'用户账号表',
                'user_id'=>$intUserId,
            ),
            'member_login_info' => Array(//'用户登录信息表',
                'user_id'=>$intUserId,
                'reg_ip'=>$this->getRequestValue('$$ip',''),
                'reg_time'=>$this->getRequestValue('reg_time'),
            ),
            'member_login_log'=>Array(
                'user_id'=>$intUserId,
                'login_time'=>$this->getRequestValue('reg_time'),
                'login_ip'=>$this->getRequestValue('$$ip',''),
                'user_agent' => $this->getRequestValue('$$agent',''),
                'has_mobile' => $this->getRequestValue('$$mobile',false)?1:2,
                'status'=>1,
            ),
        );
        if ($form != 'reg'){unset($iniTable['member_login_log']);}
        foreach ($iniTable as $k => $v){
            $result = $this->Db()->insert($k, $v);
            if ($result === false){
                $this->Db()->rollback();
                return Array("{$k}添加出错：".$this->Db()->getLastSql(), 0);
            }
        }
        $this->Db()->commit('Auth.addUser');
        return Array('初始化完成',1);
    }

}